package com.xw.unification.test.entity;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xw.unification.entity.request.CopyOnReadHttpServletRequest;
import com.xw.unification.entity.request.RepeatableRequestDelegate;
import com.xw.unification.entity.request.RepeatableRequestRewriteContext;
import com.xw.unification.entity.request.ServletInputStreamWrapper;
import com.xw.unification.interfaces.RepeatableRequestRewriter;
import com.xw.unification.test.dto.AccountDTO;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class AccountDTORewriter implements RepeatableRequestRewriter {

    private static final ObjectMapper OM = new ObjectMapper();

    @Override
    public boolean rewrite(CopyOnReadHttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, RepeatableRequestRewriteContext ctx) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            if (!(inputStream instanceof ServletInputStreamWrapper)) {
                return false;
            }
            Charset charset = StandardCharsets.UTF_8;
            String dtoJson = RepeatableRequestDelegate.stringfy((ServletInputStreamWrapper) inputStream, charset);
            AccountDTO accountDTO = OM.readValue(dtoJson, AccountDTO.class);
            accountDTO.setId(UUID.randomUUID().toString());
            RepeatableRequestDelegate.rewrite(request, OM.writeValueAsString(accountDTO).getBytes(charset));
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
